import InterceptorManager from './core/InterceptorManager'
import localStorage from '@/localStorage'
import http from './'

let interceptors = {
	request: new InterceptorManager(),
	response: new InterceptorManager()
}

// 请求拦截
interceptors.request.use(function(config) {
	var token = localStorage.getToken()
	config.header.Authorization = `Bearer ${token.token}`
	config.header['x-Authorization'] = `Bearer ` + token["x-token"]
	return config
}, undefined)

let isRequesting = false			// 是否正在请求

// 响应拦截
interceptors.response.use(async function(res) {
	if (res.data.succeeded) {
		// 请求成功
		return res.data
	} else {
		// 请求不成功，则提示错误
		uni.showToast({ 
			icon: 'none',
			position: 'bottom',
			title: res.data.errors
		})
		throw new Error(res.data.errors)
	}
	return res
}, err => {
	// 异常处理
	if (err.statusCode === 401) {
		// 无权限，未获取token或token已过期，重新获取token
		let { config } = err
		uni.login({
			provider: "weixin",
			async success(info) {
				if (isRequesting) return 
				isRequesting = true
				let [, res] = await uni.request({
					url: `${config.baseURL}/account/token`,
					data: { code: info.code },
					method: 'POST'
				})
				localStorage.setToken({ token: res.header['access-token'], 'x-token': res.header['x-access-token'] })
				http.request(config)
				isRequesting = false
			}
		})
	}
	// 其他错误直接提示网络异常
	uni.showToast({
		icon: 'none',
		position: 'bottom',
		title: '网络异常'
	})
})

export default interceptors
